import 'package:flutter/material.dart';
import 'package:dog_read/pages/book/sites/biquge.dart';
import 'package:dog_read/provider/providers.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:dog_read/pages/utils/common_utils.dart' show getPageStringOffsetList;

class ChapterContent extends StatefulWidget {
  @override
  _ChapterContentState createState() => _ChapterContentState();
}

class _ChapterContentState extends State<ChapterContent> with TickerProviderStateMixin {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  Color readBackgrounColor = Color.fromRGBO(238, 233, 191, 1);
  PageController _pageController;
  final double headerHeight = 20;
  int totalPageCount;
  int currentPage=0;

  AnimationController animationController;
  Animation animationTop;
  Animation animationBottom;
  CurvedAnimation curve;

  AnimationController settingsControl;
  Animation settingsAnimation;
  CurvedAnimation settingsCurve;

  int chapterIndex;
  List chapterList;

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]);

    // 初始化页面设置
    Provider.of<PageControlProvider>(context, listen:false).setSettings();
    // pagecontroller
    this._pageController = PageController(viewportFraction: 1, initialPage: 0);
    // 上下菜单栏的动画初始化
    animationController = AnimationController(
      duration: Duration(milliseconds: 200),
      vsync: this,
    );
    curve = CurvedAnimation(parent: animationController, curve: Curves.easeInOut);
    animationTop = Tween(begin: 0.0, end: 90.0).animate(curve);
    animationBottom = Tween(begin: 0.0, end: 160.0).animate(curve);
    // 设置动画初始化
    settingsControl = AnimationController(
      duration: Duration(milliseconds: 200),
      vsync: this
    );
    settingsControl.addStatusListener((status) async{ 
      if(status == AnimationStatus.reverse){
          SystemChrome.setEnabledSystemUIOverlays([]);
      }
      // 设置完成后的事情
      if(status == AnimationStatus.reverse){
        setState(() { // 让pageview状态正常(暂时解决)
        });
      // 保存下设置的内容
        SharedPreferences prefs = await SharedPreferences.getInstance();
        bool snap = Provider.of<PageControlProvider>(context, listen:false).pageSnapping;
        Axis direction = Provider.of<PageControlProvider>(context, listen:false).pageTurningDirection;
        double fontSize = Provider.of<PageControlProvider>(context, listen:false).fontSize;
        double lineHeight = Provider.of<PageControlProvider>(context, listen:false).lineHeight;
        prefs.setBool("pageSnap", snap);
        prefs.setDouble("pageFontSize", fontSize);
        prefs.setDouble("pageLineHeight", lineHeight);
        prefs.setBool("pageDirection", direction==Axis.vertical?true:false); // true上下滑动
        prefs.setBool("hasSettings", true);
        await Provider.of<PageControlProvider>(context, listen:false).setSettings();
      }
    });
    settingsCurve = CurvedAnimation(parent: settingsControl, curve: Curves.easeInOut);
    settingsAnimation = Tween(begin: 0.0, end: 260.0).animate(settingsCurve);
    // 初始化chapter_list和chapter_index
    chapterList= Provider.of<ChapterInfosProvider>(context, listen: false).chapterList;
    chapterIndex = Provider.of<ChapterInfosProvider>(context, listen: false).chapterIndex;
    // 初始化允许滑动
    Future.delayed(Duration(milliseconds: 100)).then((value){
      Provider.of<PageControlProvider>(context, listen: false).setAllowScroll(true);
    });
  }

  @override
  void dispose() {
    super.dispose();
    animationController.dispose();
    settingsControl.dispose();
    // SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top, SystemUiOverlay.bottom]);
    SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
  }

  void _handlePageActions(details) async{  // 处理阅读页面各种事件
    // 激活上下弹出菜单
    if(details.globalPosition.dy > (MediaQuery.of(context).size.height-180)/2 &&
        details.globalPosition.dy < (MediaQuery.of(context).size.height+180)/2 && 
        details.globalPosition.dy > (MediaQuery.of(context).size.width-160)/2 &&
        details.globalPosition.dy > (MediaQuery.of(context).size.width+160)/2) {
        if(settingsControl.status != AnimationStatus.completed){
          switch (animationController.status) {
          case AnimationStatus.completed:
            SystemChrome.setEnabledSystemUIOverlays([]);
            animationController.reverse();
            Provider.of<PageControlProvider>(context, listen: false).setAllowScroll(true);
            break;
          default:
            // SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom, SystemUiOverlay.top]);
            SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
            this.animationController.forward();
            Provider.of<PageControlProvider>(context, listen: false).setAllowScroll(false);
            break;
        }
      
      }
      if(settingsControl.status == AnimationStatus.completed && animationController.status != AnimationStatus.completed){
          settingsControl.reverse();
          Provider.of<PageControlProvider>(context, listen: false).setAllowScroll(true);
          // setState(() {
          //   // 解决变化pageview方向后翻页距离的问题
          // });
      }
      return ;
    }
    if(this.animationController.status == AnimationStatus.completed || this.settingsControl.status == AnimationStatus.completed){ 
      // 菜单处于弹出状态则禁用页面滑动
        return ;
    }
    if(Provider.of<PageControlProvider>(context, listen: false).pageTurningDirection == Axis.vertical){
      if(details.globalPosition.dy > MediaQuery.of(context).size.height*2/3 ){
        // 底部点击下一页
        this._pageController.nextPage(duration: kTabScrollDuration, curve: Curves.easeInOut);
      }
      if(details.globalPosition.dy < MediaQuery.of(context).size.height/3 && 
      this._pageController.page != 0){
        // 顶部点击上一页
        this._pageController.previousPage(duration: kTabScrollDuration, curve: Curves.easeInOut);
    }}
    if(Provider.of<PageControlProvider>(context,listen: false).pageTurningDirection == Axis.horizontal){
      if(details.globalPosition.dx < MediaQuery.of(context).size.width/2){
        if(this._pageController.page != 0){
          // 左翻页
          this._pageController.previousPage(duration: kTabScrollDuration, curve: Curves.easeInOut);
        }
        // if(this._pageController.page ==0 && this.chapterIndex !=0){
        //   Provider.of<ChapterInfosProvider>(context, listen: false).setChapterIndex(this.chapterIndex -1);
        // }
      }else{
        // 右边翻页
        this._pageController.nextPage(duration: kTabScrollDuration, curve: Curves.easeInOut);
        // int chapterIndex = Provider.of<ChapterInfosProvider>(context, listen: false).chapterIndex;
        // Provider.of<ChapterInfosProvider>(context, listen: false).setChapterIndex()
      }
    }

  }

  Widget topSmallHeader(title){  // 上方阅读信息小栏
    return Consumer<PageControlProvider>(builder: (context,pageControlProvider,child ){
      return SizedBox(
        height: this.headerHeight,
        child: Row( 
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              margin: EdgeInsets.only(left: 8),
              child: Text(
                "$title",
                style: TextStyle(fontSize: 14),
                )
              ),
            Container(
              margin: EdgeInsets.only(right: 16),
              child: Text(
                "当前${pageControlProvider.currentChapterPage}/${this.totalPageCount}页",
                style: TextStyle(fontSize: 14),
                )
            )
          ])
      );});
  }

  void _openSettings(){
    this.settingsControl.forward();
  }

  @override
  Widget build(BuildContext context) {
    this.chapterIndex = Provider.of<ChapterInfosProvider>(context, listen: true).chapterIndex ?? this.chapterIndex;
    Future.delayed(Duration(milliseconds: 50)).then((e) {
      Provider.of<PageControlProvider>(context, listen: false).setCurrentChapterPage(1);
    });
    
    return Scaffold(
      key: _scaffoldKey,
      drawer: ChapterListDrawer(),
      backgroundColor: this.readBackgrounColor,
      body: Stack(
        children: <Widget>[
          SafeArea( 
            child: 
              FutureBuilder(
                future: BiqugeSpider.getChapterContent(chapterList[this.chapterIndex]["chapter_url"]),
                builder: (ctx, snapshot){
                  if (snapshot.connectionState != ConnectionState.done) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                  }
                  Map chapterInfos = snapshot.data;
                  return  LayoutBuilder(
                    builder: (BuildContext context, BoxConstraints constraints) {
                      return Consumer<PageControlProvider>( 
                        builder: (context,pageControlProvider,child ){
                          // 计算文章的分页
                          TextStyle textStyle = TextStyle(
                            fontSize: pageControlProvider.fontSize,
                            height: pageControlProvider.lineHeight
                          );
                          List<String> totalPageList = getPageStringOffsetList(
                          chapterInfos["chapterContent"], 
                          constraints.maxWidth-16, 
                          constraints.maxHeight-this.headerHeight, 
                          textStyle
                          );
                          this.totalPageCount = totalPageList.length;
                          this._pageController = PageController(viewportFraction: 1, initialPage: 0);
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            this.topSmallHeader(chapterInfos["chapterTitle"]),
                            Expanded(
                              child: GestureDetector( 
                              onTapUp: _handlePageActions,
                              child: PageView.builder(
                                controller: _pageController,
                                pageSnapping: pageControlProvider.pageSnapping,
                                scrollDirection: pageControlProvider.pageTurningDirection,
                                itemCount: this.totalPageCount,
                                physics: pageControlProvider.isAllowScroll? ScrollPhysics(): NeverScrollableScrollPhysics(),
                                onPageChanged: (int page){
                                  pageControlProvider.setCurrentChapterPage(page+1);
                                },
                                itemBuilder: (ctx, index){
                                  return Container(
                                    padding: EdgeInsets.only(left: 8, right: 8),
                                    margin: EdgeInsets.only(top:0),
                                    child: Text(
                                      totalPageList[index],
                                      style: textStyle,
                                    ),
                                  );
                                  })
                            )
                   )
              ]
              );});
              });}
              )
          ),    
          AnimatedTop(  // 顶部菜单
            animations: [animationTop],
            controller: animationController,
          ),
          AnimatedBottom( // 底部菜单
            animations: [animationBottom],
            controller: animationController,
            scaffoldKey: _scaffoldKey,
            pageController: _pageController,
            chapterList: this.chapterList,
            openSettings : _openSettings
            ),
          AnimatedSettings( // 底部设置
            controller: settingsControl,
            animations: [settingsAnimation],
          )
          ],
          ),
    );
  }
}



class ChapterListDrawer extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    List chapterList = Provider.of<ChapterInfosProvider>(context, listen: false).chapterList;
    int currentIndex = Provider.of<ChapterInfosProvider>(context, listen: false).chapterIndex;
    String bookTitle = Provider.of<ChapterInfosProvider>(context, listen: false).bookTitile;
    double offset = 40.0 * currentIndex;
    ScrollController _controller = ScrollController(initialScrollOffset: offset);
    return Drawer(
    child: MediaQuery.removePadding(
        removeTop: true,
        context: context,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: MediaQuery.of(context).padding.top,
            ),
            SizedBox(
              height: 60,
              child: Container(
                margin: EdgeInsets.all(8.0),
                child: Text(
                  bookTitle,
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ),
            Expanded(
                flex: 80,
                child: ListView.builder(
                  controller: _controller,
                    itemCount: chapterList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                          padding: EdgeInsets.all(8),
                          height: 40,
                          width: double.infinity,
                          child:   
                            GestureDetector(
                              onTap: (){
                                Provider.of<ChapterInfosProvider>(context, listen: false).setChapterIndex(index);
                                Navigator.pop(context);
                              },
                              child: index != currentIndex?Text(
                                chapterList[index]["title"],
                                style: TextStyle(
                                  fontSize: 16,
                                  color: Colors.grey
                                ),
                              ):
                              Text(
                                chapterList[index]["title"],
                                style: TextStyle(
                                  fontWeight: FontWeight.w400,
                                  fontSize: 18
                                ),
                            ),
                            )
                            
                        );
                    }))
          ],
        )));
        }
}


class AnimatedSettings extends AnimatedWidget{
  final AnimationController controller;
  final List animations;

  AnimatedSettings({this.animations, this.controller}): super(listenable: controller);
  @override
  Widget build(BuildContext context) {
    double currentFontSize = Provider.of<PageControlProvider>(context).fontSize;
    double lineHeight = Provider.of<PageControlProvider>(context).lineHeight;
    Axis pageTurningDirection = Provider.of<PageControlProvider>(context).pageTurningDirection;
    bool snap = Provider.of<PageControlProvider>(context).pageSnapping;
    return Positioned(
            bottom: 0,
            child:Opacity(
              opacity: 0.9,
              child: Container(
                height: animations[0].value,
                width: MediaQuery.of(context).size.width,
                decoration: BoxDecoration(color: Colors.white),
                child: animations[0].value < 200 ? Container():
                Column(
                  children: <Widget>[
                    SizedBox(height: 10,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(left:16, right: 20),
                          child: Text("字号", style: TextStyle(fontSize: 16),),
                        ),
                        ActionChip(
                          label: Text("-", style: TextStyle(fontSize: 20)),
                          onPressed: (){
                            if(currentFontSize>12){
                            Provider.of<PageControlProvider>(context, listen: false).setFontSize(
                              currentFontSize-1
                            );}
                          },
                        ),
                        Slider(
                        value: currentFontSize,
                        onChanged: (value){
                          Provider.of<PageControlProvider>(context, listen: false).setFontSize(value);
                        },
                        activeColor: Theme.of(context).accentColor,
                        inactiveColor:Theme.of(context).accentColor.withOpacity(0.5),
                        divisions: 20,
                        min: 12,
                        max: 32,
                        label: "$currentFontSize",
                      ),
                        ActionChip(
                              label: Text("+", style: TextStyle(fontSize: 20),),
                              onPressed: (){
                                if(currentFontSize<32){
                                Provider.of<PageControlProvider>(context, listen: false).setFontSize(
                                  currentFontSize+1
                                );}
                              },
                            ),
                        Container(
                          margin: EdgeInsets.only(left: 20, right:16),
                          child: Text("${currentFontSize.toInt()}", style: TextStyle(fontSize: 16),),
                        )
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(left:16, right: 20),
                          child: Text("行距", style: TextStyle(fontSize: 16),),
                        ),
                        ActionChip(
                          label: Text("-", style: TextStyle(fontSize: 20)),
                          onPressed: (){
                            if(lineHeight > 1){
                            Provider.of<PageControlProvider>(context, listen: false).setLineHeight(
                              (lineHeight*10-1)/10
                            );}
                          },
                        ),
                        Slider(
                        value: lineHeight,
                        onChanged: (value){
                          Provider.of<PageControlProvider>(context, listen: false).setLineHeight(value);
                        },
                        activeColor: Theme.of(context).accentColor,
                        inactiveColor:Theme.of(context).accentColor.withOpacity(0.5),
                        divisions: 40,
                        min: 1,
                        max: 5,
                        label: "$lineHeight",
                      ),
                        ActionChip(
                              label: Text("+", style: TextStyle(fontSize: 20),),
                              onPressed: (){
                                if(lineHeight<5){
                                Provider.of<PageControlProvider>(context, listen: false).setLineHeight(
                                  (lineHeight*10+1)/10
                                );}
                              },
                            ),
                        Container(
                          margin: EdgeInsets.only(left: 20, right:16),
                          child: Text("$lineHeight", style: TextStyle(fontSize: 16),),
                        )
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(left:16, right: 20),
                          child: Text("翻页", style: TextStyle(fontSize: 16),),
                        ),
                        ChoiceChip(
                          label: Text("左右", style: TextStyle(fontSize: 18),),
                          selectedColor: Colors.black,
                          selected: pageTurningDirection == Axis.horizontal,
                          onSelected: (value){
                            Provider.of<PageControlProvider>(context, listen: false).setPageTurningDirection(Axis.horizontal);
                            Provider.of<PageControlProvider>(context, listen: false).setPageSnapping(true);
                          },
                        ),
                        SizedBox(width: 30,),
                        ChoiceChip(
                          label: Text("上下", style: TextStyle(fontSize: 18),),
                          selectedColor: Colors.black,
                          selected: pageTurningDirection == Axis.vertical,
                          onSelected: (value){
                            Provider.of<PageControlProvider>(context, listen: false).setPageTurningDirection(Axis.vertical);
                          },
                        )
                      ],
                    ),
                    Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                           Container(
                            margin: EdgeInsets.only(left:16, right: 20),
                            child: Text("滑动", style: TextStyle(fontSize: 16),),
                          ),
                          ChoiceChip(
                            label: Text("跟手", style: TextStyle(fontSize: 18),),
                            selectedColor: Colors.black,
                            selected: !snap,
                            onSelected: (value){
                              if(pageTurningDirection != Axis.horizontal){
                              Provider.of<PageControlProvider>(context, listen: false).setPageSnapping(false);
                              }else{
                                Toast.show("别按了兄弟~", context, duration: Toast.LENGTH_SHORT, gravity:  Toast.BOTTOM);
                              }
                            },
                          ),
                          SizedBox(width: 30,),
                          ChoiceChip(
                            label: Text("渐入", style: TextStyle(fontSize: 18),),
                            selectedColor: Colors.black,
                            selected: snap,
                            onSelected: (value){
                              Provider.of<PageControlProvider>(context, listen: false).setPageSnapping(true);
                            },
                          )
                        ],
                    )
                  ],
                )
            )));
  }

}

class AnimatedTop extends AnimatedWidget {
  final List animations;
  final AnimationController controller;

  AnimatedTop({this.animations, this.controller})
      : super(listenable: controller);

  @override
  Widget build(BuildContext context) {
    return Opacity(
        opacity: 0.9,
        child: Container(
            padding: EdgeInsets.all(0),
            height: animations[0].value,
            width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(color: Colors.white),
            child: AppBar(
                    backgroundColor: Colors.white,
                    automaticallyImplyLeading:false,
                    leading: IconButton(
                    icon: Icon(Icons.arrow_back_ios),
                    onPressed: (){
                        Navigator.pop(context);
                      },
                    ),
                  ),
            ));
  }
}

class AnimatedBottom extends AnimatedWidget {
  final List animations;
  final AnimationController controller;
  final GlobalKey<ScaffoldState> scaffoldKey;
  final PageController pageController;
  final List chapterList;
  final openSettings;

  AnimatedBottom(
      {this.animations, this.controller, this.scaffoldKey, this.pageController, this.chapterList, this.openSettings})
      : super(listenable: controller);

  @override
  Widget build(BuildContext context) {
    double max = this.chapterList.length.toDouble() - 1;
    int chapterIndex = Provider.of<ChapterInfosProvider>(context, listen: true).chapterIndex;
    return  Positioned(
        bottom: 0,
        child:Opacity(
          opacity: 0.9,
          child: Container(
          height: animations[0].value,
          width: MediaQuery.of(context).size.width,
          decoration: BoxDecoration(color: Colors.white),
          child: BottomAppBar(
            child: Container(
              child: Column(
                children: <Widget>[
                  Expanded(
                    flex: 2,
                    child: 
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                    Expanded(
                    flex: 1,
                    child: IconButton(
                      icon: Text("上一章"),
                      onPressed: (){
                        if(chapterIndex > 0){
                          Provider.of<ChapterInfosProvider>(context, listen: false).setChapterIndex(chapterIndex-1);
                        }
                      },
                    ),
                    ),
                    Expanded(
                      flex: 3,
                      child: animations[0].value >= 160 ? 
                        Slider(
                          value: chapterIndex.toDouble(),
                          onChanged: (value){
                            print("当前 $value");
                            Provider.of<ChapterInfosProvider>(context, listen: false).setChapterIndex(value.toInt());
                          },
                          activeColor: Theme.of(context).accentColor,
                          inactiveColor:Theme.of(context).accentColor.withOpacity(0.5),
                          divisions: max.toInt(),
                          min: 0.0,
                          max: max,
                          label: chapterList[chapterIndex]["title"],
                        ) : Container(),
                    ),
                    Expanded(
                      flex: 1,
                      child: IconButton(
                        icon: Text("下一章"),
                        onPressed: (){
                          if(chapterIndex < chapterList.length-1){
                          Provider.of<ChapterInfosProvider>(context, listen: false).setChapterIndex(chapterIndex+1);
                          }
                        },
                      ),
                      )
                  ],
                ),
                    ),
                    Expanded(
                      flex:2,
                      child:
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          IconButton(
                            icon: Text("目录"),
                            onPressed: (){
                              scaffoldKey.currentState.openDrawer();
                              controller.reverse();
                            },
                        ),
                          IconButton(
                            icon: Text("设置"),
                            onPressed: (){
                              controller.reverse();
                              openSettings();
                            },
                          )
                      ],
                    ))
                    ],
                  )
          ))
    )));
  }
}
